package com.lmabbe.common.global.context.session;

import com.lmabbe.common.global.constant.GlobalConstant;
import com.lmabbe.common.global.context.LmabbeSessionUser;
import com.lmabbe.common.global.enums.ClientTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * web端实现session上下文
 *
 * @author lmabbe
 */
public class WebLmabbeSessionUserImpl implements LmabbeSessionUser {


    @Autowired
    private TokenStore tokenStore;

    @Override
    public Long getTenantId() {
        return Long.parseLong(getRequest().getHeader(GlobalConstant.SYSTEM.TENANT_ID));
    }

    @Override
    public String token() {
        return getRequest().getHeader(GlobalConstant.SYSTEM.AUTHORIZATION).replace(GlobalConstant.SYSTEM.AUTHENTICATION_PREFIX, "");
    }

    @Override
    public ClientTypeEnum clientType() {
        return ClientTypeEnum.getClientTypeByCode(getRequest().getHeader(GlobalConstant.SYSTEM.FROM_CLIENT));
    }

    @Override
    public LoginUser loginUser() {
        OAuth2Authentication auth2Authentication = tokenStore.readAuthentication(this.token());
        JwtUser principal = (JwtUser) auth2Authentication.getPrincipal();
        return principal.getLoginUser();
    }

    private HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }
}
